﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.IO;
using System.Linq;
using System.Web;

namespace WebForm.Common
{
    public class ImageHelper
    {
        public static void CropImage(string originamImgPath, int width, int height, int x, int y, int showWidth, int showHeight)
        {
            byte[] CropImage = Crop(originamImgPath, width, height, x, y, showWidth, showHeight);
            using (MemoryStream ms = new MemoryStream(CropImage, 0, CropImage.Length))
            {
                ms.Write(CropImage, 0, CropImage.Length);
                using (System.Drawing.Image CroppedImage = System.Drawing.Image.FromStream(ms, true))
                {

                    CroppedImage.Save(originamImgPath, CroppedImage.RawFormat);
                }
            }
        }
        private static byte[] Crop(string Img, int Width, int Height, int X, int Y, int showWidth, int showHeight)
        {
            try
            {
                using (Image OriginalImage = Image.FromFile(Img))
                {

                    int picW = OriginalImage.Size.Width;
                    int picH = OriginalImage.Size.Height;
                    //int picW= 1920;  
                    //int picH = 1080;  


                    int picWidth = Width * picW / showWidth;
                    int picHeight = Height * picH / showHeight;
                    int picX = X * picW / showWidth;
                    int picY = Y * picH / showHeight;

                    using (Bitmap bmp = new Bitmap(picWidth, picHeight, OriginalImage.PixelFormat))
                    {
                        bmp.SetResolution(OriginalImage.HorizontalResolution, OriginalImage.VerticalResolution);
                        using (Graphics Graphic = Graphics.FromImage(bmp))
                        {
                            Graphic.SmoothingMode = SmoothingMode.AntiAlias;
                            Graphic.InterpolationMode = InterpolationMode.HighQualityBicubic;
                            Graphic.PixelOffsetMode = PixelOffsetMode.HighQuality;
                            Graphic.DrawImage(OriginalImage, new Rectangle(0, 0, picWidth, picHeight), picX, picY, picWidth, picHeight, GraphicsUnit.Pixel);
                            MemoryStream ms = new MemoryStream();
                            bmp.Save(ms, OriginalImage.RawFormat);
                            return ms.GetBuffer();
                        }
                    }
                }
            }
            catch (Exception Ex)
            {
                throw (Ex);
            }
        }
    }  
}